<template>
    <div class="detail">
        <div class="info">
            <div class="price"><text class="sell">￥{{ detail.sellingPrice }}</text><text class="orgin"
                    v-if="detail.sellingPrice != detail.originalPrice">{{ '￥' +
                        detail.originalPrice
                    }}</text> <nut-tag v-if="user.t == 'takerUser'" color="#FA685D" style="margin-right: 10rpx;">赚{{
    detail.distPrice }}元起</nut-tag>
                <nut-tag v-if="detail.quota != null && detail.quota != 0" color="#FA685D">限购{{ detail.quota }}件</nut-tag>
            </div>
            <div class="goods-title flex-a flex-b">
                <div>
                    {{ detail.goodsName }}
                </div>
                <StarN v-if="detail.goodStatus == 0" size="22px" color="#5E5E5E" @click="collect" />
                <StarFillN v-if="detail.goodStatus == 1" size="22px" color="#FFA80D" @click="resetCollect" />
            </div>
            <div class="des">{{ detail.goodsIntro }}</div>
            <!-- <div class="time"><nut-countdown :end-time="end" /></div> -->
            <div class="coupon flex-a flex-b" v-if="detail.list.length > 0">
                <div class="flex-a">
                    <text v-for="item in detail.list">{{ item.min + '减' + item.discount }}</text>
                </div>
                <div class="flex-a" @click="showCoupon">
                    <text>{{ detail.list.length }}个优惠</text>
                    <RectDown size="14" />
                </div>
            </div>
        </div>
        <rich-text :nodes="html"></rich-text>
        <nut-popup position="bottom" :style="{ width: '100%', height: '70%' }" v-model:visible="showBottom" closeable round
            class="popup-box">
            <div class="head">
                <div>{{ detail.goodsName }}</div>
                <div><text class="sell">￥{{ detail.sellingPrice }}</text><text class="orgin"
                        v-if="detail.sellingPrice != detail.originalPrice">{{ '￥' +
                            detail.originalPrice
                        }}</text><nut-tag v-if="user.t == 'takerUser'" color="#FA685D">赚{{ detail.distPrice }}元</nut-tag>
                </div>
            </div>
            <div class="add-address flex-a" @click="jumpTo" v-if="type == 'buy'">
                <div class="address flex-a flex-b" v-if="addrInfo && addrInfo.addressId" @click="jumpTo">
                    <div class="left">
                        <div class="name flex-a"><span>{{ addrInfo.userName }}</span><span>{{ addrInfo.userPhone }}</span>
                        </div>
                        <div class="addr">{{ addrInfo.provinceName + addrInfo.cityName + addrInfo.regionName +
                            addrInfo.detailAddress }}</div>
                    </div>
                    <div>
                        <Right color="#333333" size="15px" />
                    </div>
                </div>
                <div v-else class="flex-a">
                    <Uploader color="#333333" size="15px" />
                    <div style="margin-left: 10rpx;">添加收货地址</div>
                </div>
            </div>
            <div class="spec">
                <div class="title">选择规格：</div>
                <div class="spec-list">
                    <span v-for="(item, index) in detail.specInfoList" :key="item.id"
                        :class="index == select ? 'active' : ''" @click="selectSpec(item, index)">{{ item.specName
                        }}</span>
                </div>
            </div>
            <div class="foot flex-a flex-b">
                <div class="buy">购买数量</div>
                <div><nut-input-number v-model="num" :min="0" /></div>
                <div><nut-button type="info" @click="submitCart">确定</nut-button></div>
            </div>
        </nut-popup>
        <nut-popup position="bottom" :style="{ width: '100%', height: '50%' }" v-model:visible="couponShow" closeable round
            class="popup-coupon">
            <div class="title">红包优惠</div>
            <div class="list">
                <div class="item flex-b" v-for="(item, index) in detail.list" :key="item">
                    <div class="flex-a">
                        <div class="left">
                            <div>￥{{ item.discount }}</div>
                            <div></div>
                        </div>
                        <div class="middle">
                            <div>{{ item.couponName }}</div>
                            <div>{{ item.couponEndTime || '长期有效' }}</div>
                        </div>
                    </div>
                    <div class="right">
                        <div v-if="item.status == 0" @click="receive(item.couponId, index)">立即领取</div>
                        <img v-else src="https://cxj.szzkba.cn/up/uploadPath/icon/pPEflY4.png" alt="">
                    </div>
                </div>
            </div>
        </nut-popup>
    </div>
</template>

<script lang="ts">
import Taro, { useRouter } from '@tarojs/taro';
import mitt from "./../../../../utils/mitt";
import { RectDown, Right, StarN, StarFillN, } from '@nutui/icons-vue-taro';
import { reactive, toRefs, onMounted } from 'vue';
import { getDetail, getDetailNo, uploadCart, getCoupon, defaultAddr, getAddressList, saveOrderOnCk, getCart, ckGoods } from '../../../../api/index'
export default {
    components: {
        RectDown, Right, StarN, StarFillN,
    },
    emits: ['title'],
    setup(props, ctx) {
        const data = reactive({
            end: Date.now() + 30 * 60 * 1000,
            goodsId: '',
            detail: {
                list: []
            },
            html: '',
            showBottom: false,
            couponShow: false,
            list: [
                {
                    id: 0,
                    name: '25ml/6片'
                },
                {
                    id: 1,
                    name: '25ml/6片'
                },
                {
                    id: 2,
                    name: '25ml/6片'
                }
            ],
            select: 0,
            specId: '',
            num: 1,
            type: '',
            addrInfo: {},
            addressId: '',
            user: {}
        });
        onMounted(() => {
            Taro.getStorage({
                key: 'user',
                success: function (res) {
                    data.user = res.data
                }
            })
            const router = useRouter();
            if (router.params.scene) {
                data.goodsId = router.params.scene.split('%26')[0].split('%3D')[1]
                getProductDetail(router.params.scene.split('%26')[0].split('%3D')[1])
            }
            console.log(router.params.goodsId)
            if (router.params.goodsId) {
                data.goodsId = router.params.goodsId
                getProductDetail(router.params.goodsId)
            }
            if (router.params.type) {
                data.type = router.params.type
            }
            if (router.params.addressId) {
                data.addressId = router.params.addressId
                data.showBottom = true
                getAddressList().then(response => {
                    if (response.resultCode == 200 && response.data) {
                        let list = response.data
                        data.addrInfo = list.filter(item => item.addressId == router.params.addressId)[0]
                    }
                })
            } else {
                Taro.getStorage({
                    key: 'user',
                    success: function (res) {
                        if (res.data) {
                            defaultAddr().then(res => {
                                if (res.resultCode == 200) {
                                    data.addrInfo = res.data
                                }
                            })
                            getList()
                        }
                    }
                })

            }

        });
        const collect = () => {
            ckGoods(data.goodsId).then(res => {
                if (res.resultCode == 200) {
                    Taro.showToast({
                        title: '收藏成功',
                        icon: 'success',
                        duration: 2000
                    })
                    data.detail.goodStatus = 1
                }
            })
        }
        const resetCollect = () => {
            ckGoods(data.goodsId).then(res => {
                if (res.resultCode == 200) {
                    Taro.showToast({
                        title: '取消收藏',
                        icon: 'success',
                        duration: 2000
                    })
                    data.detail.goodStatus = 0
                }
            })
        }
        const getList = () => {
            getCart().then(res => {
                if (res.resultCode == 200) {
                    mitt.emit('cartNum', res.data.list.length)
                }
            })
        }
        const getProductDetail = (id) => {
            Taro.getStorage({
                key: 'token',
                success: function (res) {
                    getDetail(id).then(res => {
                        if (res.resultCode == 200) {
                            data.detail = res.data
                            data.detail.sellingPrice = res.data.specInfoList[0].specSellingPrice
                            data.detail.originalPrice = res.data.specInfoList[0].specOriginalPrice
                            mitt.emit('detail', res.data)
                            ctx.emit('title', res.data.goodsName)
                            data.html = formatImg(res.data.goodsDetailContent)
                        }
                    })
                },
                fail: function (rej) {
                    getDetailNo(id).then(res => {
                        if (res.resultCode == 200) {
                            data.detail = res.data
                            data.detail.sellingPrice = res.data.specInfoList[0].specSellingPrice
                            data.detail.originalPrice = res.data.specInfoList[0].specOriginalPrice
                            mitt.emit('detail', res.data)
                            ctx.emit('title', res.data.goodsName)
                            data.html = formatImg(res.data.goodsDetailContent)
                        }
                    })
                }
            })
        };
        const formatImg = (html) => {
            var newContent = html.replace(/<img[^>]*>/gi, (match) => {
                let processed = null;
                if (!match.match(/style=\"(.*)\"/gi)) {
                    processed = match.replace(/\<img/g, '<img style="width:100%;height:auto;display:block"');
                } else {
                    processed = match.replace(/style=\"(.*)\"/gi, 'style="width:100%;height:auto;display:block"');
                }
                return processed;
            });
            return newContent;
        }
        const selectSpec = (item, index) => {
            data.select = index
            data.specId = item.specId
            data.detail.sellingPrice = item.specSellingPrice
            data.detail.originalPrice = item.specOriginalPrice
            data.detail.distPrice = item.distPrice
        }
        mitt.on("show", (val) => {
            data.type = val[0]
            data.showBottom = val[1]
        })
        const submitCart = () => {
            if (data.type == 'cart') {
                uploadCart({ goodsCount: parseInt(data.num), goodsId: data.detail.goodsId, cartItemId: 0, specId: data.specId || data.detail.specInfoList[0].specId }).then(res => {
                    if (res.resultCode == 200) {
                        Taro.showToast({
                            title: '添加成功',
                            icon: 'success',
                            duration: 2000
                        })
                        getList()
                        data.showBottom = false
                    } else if (res.resultCode == 500) {
                        Taro.showToast({
                            title: res.message,
                            icon: 'error',
                            duration: 2000
                        })
                    }
                })
            }
            else {
                if (data.addrInfo && data.addrInfo.addressId) {
                    saveOrderOnCk({
                        addressId: data.addrInfo.addressId, goodsId: data.goodsId, num: data.num, specId: data.specId || data.detail.specInfoList[0].specId
                    }).then(res => {
                        if (res.resultCode == 200) {
                            Taro.redirectTo({
                                url: '/packageA/pages/confirmPay/index?addressId=' + data.addrInfo.addressId + '&orderId=' + res.data,
                            })
                        } else if (res.resultCode == 500) {
                            Taro.showToast({
                                title: res.message,
                                icon: 'error',
                                duration: 2000
                            })
                        }
                    })
                } else {
                    Taro.showToast({
                        title: '请添加收货地址！',
                        icon: 'error',
                        duration: 2000
                    })
                }
            }
        }
        const showCoupon = () => {
            data.couponShow = true
        }
        const receive = (couponId, index) => {
            getCoupon({ couponId: couponId }).then(res => {
                if (res.resultCode == 200) {
                    Taro.showToast({
                        title: '领取成功',
                        icon: 'success',
                        duration: 2000
                    })
                    data.detail.list[index].status = '1'
                }
            })
        }
        const jumpTo = () => {
            Taro.navigateTo({ url: '/packageA/pages/addressList/index?type=' + data.type + '&goodsId=' + data.goodsId });
        }
        return {
            ...toRefs(data), getProductDetail, formatImg, selectSpec, submitCart, showCoupon, receive, jumpTo, getList, collect, resetCollect
        }
    }
};
</script>


<style lang="scss" >
.detail {
    .info {
        padding: 30rpx 30rpx 20rpx;
        margin: 20rpx 0;
        background: #F9F9F9;
        border-radius: 20rpx;

        .goods-title {
            color: #000;
            font-size: 34rpx;
            font-weight: bold;

            div {
                width: 90%;
                word-break: keep-all;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }

        .des {
            color: #747774;
            font-size: 28rpx;
            margin: 10rpx 0;
        }

        .price {
            color: #F25C26;
            font-size: 26rpx;
            margin-bottom: 20rpx;

            .sell {
                font-size: 30rpx;
                font-weight: bold;
                color: #F25C26;
            }

            .orgin {
                font-size: 28rpx;
                margin: 0 10rpx;
                color: #909090;
                text-decoration: line-through;
            }
        }

        .coupon {
            margin-top: 10rpx;

            div:first-child {
                text {
                    color: red;
                    font-size: 24rpx;
                    border: 1rpx solid red;
                    border-radius: 10rpx;
                    padding: 2rpx 4rpx;
                    margin-right: 5rpx;
                }
            }

            div:last-child {
                color: #333;
                font-size: 24rpx;

                text {
                    margin-right: 5rpx;
                }
            }
        }
    }

    .popup-coupon {

        .title {
            text-align: center;
            margin: 20rpx auto 30rpx;
        }

        .list {
            .item {
                margin: 0 auto 10rpx;
                background: #fff;
                box-shadow: 0 0 20rpx 20rpx #F9F9F9;
                border-radius: 20rpx;
                width: 94%;
                padding: 20rpx 0 20rpx 30rpx;
                box-sizing: border-box;

                .left {
                    margin-right: 60rpx;

                    div:first-child {
                        color: #FB452E;
                        font-size: 36rpx;
                    }

                    div:last-child {
                        color: #9C9C9C;
                        font-size: 24rpx;
                    }
                }

                .middle {
                    div:first-child {
                        color: #333;
                        font-weight: bold;
                        font-size: 30rpx;
                    }

                    div:last-child {
                        color: #FB452E;
                        font-size: 24rpx;
                    }
                }

                .right {
                    width: 30%;
                    border-left: 1rpx dashed #EAEAEA;
                    position: relative;

                    div {
                        display: inline-block;
                        border-radius: 30rpx;
                        padding: 4rpx 15rpx;
                        border: 1rpx solid #FB452E;
                        font-size: 24rpx;
                        color: #FB452E;
                        white-space: nowrap;
                        position: absolute;
                        left: 50%;
                        top: 50%;
                        transform: translate(-50%, -50%);
                        z-index: 999999;
                    }

                    img {
                        width: 80rpx;
                        height: 80rpx;
                        position: absolute;
                        right: 0;
                        bottom: 0;
                        transform: rotate(-10deg);
                    }
                }
            }
        }
    }

    .popup-box {
        .head {
            background: #FAFAFA;
            padding: 30rpx 20rpx;

            div:first-child {
                color: #000;
                font-size: 30rpx;
                font-weight: bold;
                margin-bottom: 10rpx;
                padding-right: 50rpx;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            div:last-child {
                .sell {
                    font-size: 30rpx;
                    font-weight: bold;
                    color: #F25C26;
                }

                .orgin {
                    margin: 0 10rpx;
                    font-size: 26rpx;
                    text-decoration: line-through;
                    color: #909090;
                }
            }
        }

        .add-address {
            border-top: 1rpx solid #E9E9E9;
            border-bottom: 1rpx solid #E9E9E9;
            padding: 30rpx 10rpx 30rpx 30rpx;

            .address {
                white-space: nowrap;

                .left {
                    width: 600rpx;
                }

                .name {
                    span:first-child {
                        color: #212121;
                        font-size: 34rpx;
                    }

                    span:last-child {
                        color: #808080;
                        font-size: 28rpx;
                    }
                }

                .addr {
                    font-size: 34rpx;
                }
            }
        }


        .spec {
            padding: 30rpx 20rpx;

            .title {
                font-size: 30rpx;
                margin-bottom: 40rpx;
            }

            .spec-list {
                height: 500rpx;
                overflow-y: auto;

                span {
                    margin: 0 20rpx 20rpx 0;
                    display: inline-block;
                    color: #929292;
                    border: 1rpx solid #AAAAAA;
                    padding: 20rpx 30rpx;
                    border-radius: 8rpx;
                    font-size: 26rpx;
                    box-sizing: border-box;
                }

                span.active {
                    background: #fff;
                    border-color: #196BFE;
                    font-weight: bold;
                    color: #196BFE;
                }
            }
        }

        .foot {
            background: #FAFAFA;
            padding: 30rpx 20rpx;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            box-sizing: border-box;

            .nut-button {
                width: 300rpx;
                border-radius: 10rpx;
            }
        }
    }
}
</style>